import {C, getImageData, drawPen} from '../utils'

let mouse_s = {x:0, y:0, down: false}
let mouse = {};
let item = null;
let pos = [];
let _this = null;

function start(_this, e){
  let {x, y} = C.eventWrapper(e, _this.scale)
  mouse_s.x = x;
  mouse_s.y = y;
  pos.push({x, y})
  mouse_s.down = true;
  _this.imgData = getImageData(_this.canvas);
}

function move(ctx, width, height, color, lineWidth){
  drawPen(ctx, {x: mouse_s.x, y: mouse_s.y}, {x: mouse.x, y: mouse.y}, color, lineWidth)
  pos.push({x: mouse.x, y: mouse.y})
  mouse_s.x = mouse.x;
  mouse_s.y = mouse.y;
  item = {type: 'Pen', pos, ys: color, xw: lineWidth}
}

function end(){
  if(!mouse_s.down)return;
  if(item){
    this.save(item);
  }
  mouse_s.down = false;
  item = null;
}

export default {
  click(){
    _this = this;
    mouse = C.getOffset(this.canvas, this.scale)
    this.disabledCtrl('Rotate', true)
  },
  canvasMousedown(e){
    pos = [];
    start(this, e)
  },
  canvasMouseup(e){},
  canvasMouseout(e){},
  canvasTouchstart(e){
    let target = e.target;
    if(e.changedTouches && e.changedTouches.length > 0){
      e = e.changedTouches[0]
      start(this, {pageX: e.pageX, pageY: e.pageY, target})
    }
  },
  canvasTouchend(e){},
  winMouseup(){
    end.apply(this)
  },
  winMousemove(){
    if(!mouse_s.down)return;
    const {color, lineWidth} = this.defDrawOptions
    const {width, height} = this.canvasRect
    move(this.ctx, width, height, color, lineWidth, this.imgData)
  },
  winTouchMove(e){
    if(!mouse_s.down)return;
    let target = e.target;
    const {color, lineWidth} = this.defDrawOptions
    const {width, height} = this.canvasRect
    if(e.changedTouches && e.changedTouches.length > 0){
      e = e.changedTouches[0]
      mouse = C.eventWrapper({pageX: e.pageX, pageY: e.pageY, target})
      move(this.ctx, width, height, color, lineWidth, this.imgData)
    }
  },
  winTouchend(e){},
  visibilitychange(){}
}
